package com.hema.auction.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hema.auction.R;
import com.hema.auction.activity.ConfirmOrderActivity;
import com.hema.auction.activity.GoodsDetailsActivity;
import com.hema.auction.activity.OrderDetailActivity;
import com.hema.auction.activity.PulishSunActivity;
import com.hema.auction.adapter.MyAuctionAdapter;
import com.hema.auction.base.BaseFragment;
import com.hema.auction.bean.GoodsInfo;
import com.hema.auction.bean.OrderInfo;
import com.hema.auction.http.HttpTag;
import com.hema.auction.http.biz.HttpManager;
import com.hema.auction.utils.Constant;
import com.hema.auction.utils.manager.SPManager;
import com.hema.auction.widget.view.EmptyView;
import com.hema.auction.widget.view.MyLoadMoreView;
import com.hema.auction.widget.view.RefreshRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;

/**
 * 我的竞拍记录
 * author by john
 */

public class MyAuctionFragment extends BaseFragment {

    @BindView(R.id.refresh_recycler_view)
    RefreshRecyclerView recyclerView;
    private MyAuctionAdapter myAuctionAdapter;
    private List<GoodsInfo> infos = new ArrayList<>();
    private int status, clickIndex;

    @Override
    protected int getLayout() {
        return R.layout.fragment_sun_square;
    }

    public static MyAuctionFragment newInstance(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt(Constant.EXTRA_STATUS, position);
        MyAuctionFragment fragment = new MyAuctionFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void init() {
        super.init();
        status = getArguments().getInt(Constant.EXTRA_STATUS);
        /**
         * 100:全部
         * 101 我在拍
         * 102:我拍中
         * 103:未拍中

         * 0:待付款
         * 1:待发货
         * 2:待签收
         * 3:待晒单
         * 6:未拍中
         */
        recyclerView.setVerLayoutManager();
        recyclerView.setOnRefreshListener(this);
        myAuctionAdapter = new MyAuctionAdapter(infos);
        myAuctionAdapter.setLoadMoreView(new MyLoadMoreView());
        EmptyView emptyView = new EmptyView(getActivity());
        emptyView.setViewType(EmptyView.ORDER);
        myAuctionAdapter.setEmptyView(emptyView);
        recyclerView.setAdapter(myAuctionAdapter);
        recyclerView.setRefresh(true);
        myAuctionAdapter.setOnLoadMoreListener(this, recyclerView.getRecyclerView());
        myAuctionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                GoodsInfo item = myAuctionAdapter.getItem(position);
                Bundle bundle = new Bundle();
                bundle.putParcelable(Constant.EXTRA_GOOD_INFO, item);
                intentTo(GoodsDetailsActivity.class, bundle);
//                if(item.getStatus() == 0)
//                    return;
//                if (item.getStatus() == 6) {
//                    /**
//                     * 竞拍中
//                     * 商品详情页面
//                     */
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable(Constant.EXTRA_GOOD_INFO, myAuctionAdapter.getItem(position));
//                    intentTo(GoodsDetailsActivity.class, bundle);
//                } else if (SPManager.getInstance(getActivity()).getUserId().equals(item.getUid())) {
//                    //0->下单成功（待付款），1->已付款，2->已发货，3->已收货，4->已过期，5->已完成（end）  ,    6未结束竞拍
//                    /**
//                     * 订单详情页面
//                     */
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable(Constant.EXTRA_GOOD_INFO, myAuctionAdapter.getItem(position));
//                    intentTo(OrderDetailActivity.class, bundle);
//                } else {
//                    /**
//                     * 未拍中
//                     */
//                    Bundle bundle = new Bundle();
//                    bundle.putParcelable(Constant.EXTRA_GOOD_INFO, myAuctionAdapter.getItem(position));
//                    intentTo(GoodsDetailsActivity.class, bundle);
//                }
            }
        });
        myAuctionAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter ada, View view, int position) {
                TextView tv = (TextView) view.findViewById(view.getId());
                GoodsInfo item = myAuctionAdapter.getItem(position);
                clickIndex = position;
                switch (tv.getText().toString()) {
                    case "立即付款":
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.EXTRA_ORDER_ID, item.getOrderId());
                        intentTo(ConfirmOrderActivity.class, bundle);
                        break;
                    case "差价购买":
//                        bundle = new Bundle();
//                        bundle.putBoolean(Constant.EXTRA_CJ_BUY, true);
//                        bundle.putParcelable(Constant.EXTRA_GOOD_INFO, myAuctionAdapter.getItem(position));
//                        intentTo(ConfirmOrderActivity.class, bundle);
                        cjBuy(item.getId());
                        break;
                    case "确认签收":
                        showProgressDialog();
                        HttpManager.getInstance(getActivity()).sureOrder(item.getOrderId(), MyAuctionFragment.this);
                        break;
                    case "我要晒单":
                        bundle = new Bundle();
                        bundle.putParcelable(Constant.EXTRA_GOOD_INFO, item);
                        intentTo(PulishSunActivity.class, bundle);
                        break;
                    case "继续竞拍":
                        bundle = new Bundle();
                        bundle.putParcelable(Constant.EXTRA_GOOD_INFO, item);
                        intentTo(GoodsDetailsActivity.class, bundle);
                        break;
                    case "查看详情":
                        if ((item.getStatus() != 6 && !SPManager.getInstance(getActivity()).getUserId().equals(item.getUid())) ||
                                item.getStatus() == 6) {
                            bundle = new Bundle();
                            bundle.putParcelable(Constant.EXTRA_GOOD_INFO, item);
                            intentTo(GoodsDetailsActivity.class, bundle);
                        } else {
                            bundle = new Bundle();
                            bundle.putParcelable(Constant.EXTRA_GOOD_INFO, item);
                            intentTo(OrderDetailActivity.class, bundle);
                        }

                        break;
                    case "申请反币":
                        break;
                }
            }
        });
    }


    /**
     * 差价购买下单
     */
    private void cjBuy(String id) {
        showProgressDialog();
        HttpManager.getInstance(getActivity()).cxBuy(id, this);
    }

    public void setRefresh() {
        recyclerView.setRefresh(true);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        pageIndex = 1;
        HttpManager.getInstance(getActivity()).getOrderList(pageIndex, pageSize, status, this);
    }

    @Override
    protected void onLoadMore() {
        super.onLoadMore();
        pageIndex++;
        HttpManager.getInstance(getActivity()).getOrderList(pageIndex, pageSize, status, this);
    }

    @Override
    protected void onSuccess(HttpTag httpTag, Call call, JSONObject result) {
        super.onSuccess(httpTag, call, result);
        switch (httpTag) {
            case TAG_GET_ORDER_LIST:
                try {
                    if (result.getInt("errcode") == 0) {
                        List<GoodsInfo> newInfos = new Gson().fromJson(result.getJSONArray("data").toString(), new TypeToken<List<GoodsInfo>>() {
                        }.getType());
                        if (pageIndex == 1) {
                            myAuctionAdapter.setNewData(newInfos);
                            if (newInfos.size() < pageSize)
                                myAuctionAdapter.setEnableLoadMore(false);
                            else
                                myAuctionAdapter.setEnableLoadMore(true);
                        } else {
                            myAuctionAdapter.addData(newInfos);
                            myAuctionAdapter.loadMoreComplete();
                            if (newInfos.size() < pageSize) {
                                myAuctionAdapter.loadMoreEnd();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_SURE_ORDER:
                try {
                    if (result.getInt("errcode") == 0) {
                        myAuctionAdapter.remove(clickIndex);
                    }
                    showToastSafe(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case TAG_CX_BUY:
                try {
                    if (result.getInt("errcode") == 0) {
                        OrderInfo info = OrderInfo.objectFromData(result.getJSONObject("data").toString());
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(Constant.EXTRA_CJ_BUY_PAY, true);
                        bundle.putParcelable(Constant.EXTRA_ORDER_INFO, info);
                        intentTo(ConfirmOrderActivity.class, bundle);
                    } else {
                        showToastSafe(result);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    protected void onFinish(HttpTag httpTag) {
        super.onFinish(httpTag);
        recyclerView.setRefresh(false);
    }
}
